package com.ruoyi.novel.service.impl;

import com.ruoyi.novel.domain.Bookshelf;
import com.ruoyi.novel.domain.NovelDTO;
import com.ruoyi.novel.mapper.BookshelfMapper;
import com.ruoyi.novel.mapper.HomePageMapper;
import com.ruoyi.novel.service.HomePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class HomePageServiceImpl implements HomePageService {
    @Autowired
    private HomePageMapper homePageMapper;
    @Autowired
    private BookshelfMapper bookshelfMapper;
    @Override
    public List<NovelDTO> ListByClick() {
        return homePageMapper.ListByClick();
    }

    @Override
    public List<NovelDTO> ListByPass() {
        return homePageMapper.ListByPass();
    }

    @Override
    public List<NovelDTO> ListByCollection() {
        return homePageMapper.ListByCollection();
    }

    @Override
    public List<NovelDTO> ListByMonth() {
        return homePageMapper.ListByMonth();
    }

    @Override
    public List<NovelDTO> ListByIntelligent(Long userId) {
        List<Bookshelf> getBookShelfByUserIds = bookshelfMapper.getBookShelfByUserId(userId);
        if(getBookShelfByUserIds == null || getBookShelfByUserIds.size() == 0){
             return   homePageMapper.ListByCollection();
        }
        List<String> novelType =new ArrayList<>();
        for(Bookshelf bookshelf : getBookShelfByUserIds){
            NovelDTO novelDTO = homePageMapper.getNovelDTO(bookshelf.getNovelId());
            if(novelDTO == null){
                continue;
            }
            novelType.add(novelDTO.getCategoryName());
        }
        // 使用 Stream 找出出现次数最多的类型
        String mostFrequentType = novelType.stream()
                .collect(Collectors.groupingBy(type -> type, Collectors.counting())) // 统计每种类型的出现次数
                .entrySet()
                .stream()
                .max(Map.Entry.comparingByValue()) // 找出出现次数最多的类型
                .map(Map.Entry::getKey) // 获取对应的类型名称
                .orElse(null); // 如果列表为空，返回 null
        if(mostFrequentType == null){
            return null;
        }
        return homePageMapper.ListByCategoryName(mostFrequentType);
    }
}
